import React, { useEffect, useState } from "react";
import { SidebarStudent } from "../../../components/Sidebar";
import { Assignment } from "../../../utils/constant";
import { GetAssignments, GetModuleInfo } from "../../../api";
import { useNavigate, useParams } from "react-router-dom";
import { Button } from "antd";
import { formatTimeString } from "../../../utils/time";
import "./index.less";

const Index: React.FC = () => {
  const [assignments, setAssignments] = useState<Assignment[]>([]);
  const [moduleInfo, setModuleInfo] = useState("");
  const params = useParams();
  const moduleId = +params.id!;
  const navigate = useNavigate();

  const fetchAssignments = async () => {
    try {
      const res = await GetAssignments({ moduleId });
      setAssignments(res.data);
    } catch (e) {
      console.error(e);
    }
  };

  const fetchModuleInfo = async () => {
    try {
      const res = await GetModuleInfo(moduleId);
      setModuleInfo(res.data['data']['code'] + ' ' + res.data['data']['name']);
    } catch (e) {
      console.error(e);
    }
  }

  useEffect(() => {
    fetchAssignments();
    fetchModuleInfo();
  }, []);

  return (
    <>
      <SidebarStudent />
      <div className="student-assignment-list">
        <h3>{moduleInfo}</h3>
        {assignments.map((item) => (
          <div key={item.id} className="student-assignment-card">
            <div className="student-assignment-card-content">
              <div className="student-assignment-card-content-item">
                Name: <b>{item.name}</b>
              </div>
              <div className="student-assignment-card-content-item">
                Due Date: {formatTimeString(item.deadline)}
              </div>
              <div className="student-assignment-card-content-item">
                Created On: {formatTimeString(item.createdAt)}
              </div>
              <div className="student-assignment-card-content-item">
                Last Updated: {formatTimeString(item.updatedAt)}
              </div>
            </div>
            <Button
              style={{ marginTop: 10 }}
              onClick={() => {
                navigate(
                  `/student/module/${moduleId}/listAssignment/${item.id}/listQuestion`
                );
              }}
            >
              Question
            </Button>
          </div>
        ))}
      </div>
    </>
  );
};

export default Index;
